<?php
/**
 * @desc csvWidget class file
 *
 * @author Vladimir Kovarsky <vkovarsky@gmail.com>
 *
 * @copyright Copyright &copy; 2009 Algo-rithm
 *
 * @version 1.0
 *
 * @desc csvWidget renders button(s) and provides functionality to generate csv file from the selected table(s),
 *			   the selector may any permissible in jQuery, multiple selection results are also supported
 *
 * Usage:
 * 1) copy all the 'csv' catalogue under /protected/extensions
 *
 * 2) register controller 'CsvController' in /protected/config/main.php:
 *          'controllerMap'=>array(
 *              'csv'=>array(
 *                  'class'=>'application.extensions.csv.CsvController',
 *                  'property1'=>'value1',
 *                  'property2'=>'value2',
 *                  ),
 *          ...........other controllers (if exist)
 *
 * 3) add button(s) to your view page (several times, if needed - as many as you wish!):
 *       <?php $this->widget('application.extensions.csv.csvWidget', array(
 *                       'property1'=>'value1',
 *                       'property2'=>'value2'));
 *        ?>
 *    where possible properties with their default values are:
 *
 * @var 'table' = '.dataGrid'                   		string      selector (understanding by jQuery $()-function)
 *		                                              		of the table(s) to be output,
 *								by default it's
 *                   		                               		<table class='dataGrid'></table>
 *								(selection result may be not single!)
 *
 * @var 'csvFile' = ''              		string      csv file name (if '', it will be 'data.csv' by default)
 * @var 'ignoredRow' = 'filterRow'  	string      class name for the rows <tr> which should be omitted in the csv output
 * @var 'ignoredCol' = 'actionCol'  	string      class name for the cells <td>, <th> to be omitted in the csv output
 * @var 'htmlOptions' = array()     	array       htmlOptions array - standard for Yii
 *
 *
 */

 class csvWidget extends CWidget
{
    /**
    * @desc The css selector (understanding by jQuery $()-function)
    * of the <table> element(s), which is to be exported to csv.
    * If several elements match, all of them will be output into csv.
    * By default, it is
    * <table class='dataGrid'></table> by default
    */
    public $table = '.dataGrid';

    public $csvFile = '';

    public $ignoredRow = 'filterRow';

    public $ignoredCol = 'actionCol';

    /**
    * @desc htmloptions array
    */
    public $htmlOptions = array();

    /**
    * @desc counter of widget instancies, is used in order to avoid code repetitions
    */
    static $count = 0;

    public function init()
    {
        $path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'media';
        $url = Yii::app()->getAssetManager()->publish($path);
        $imgUrl = $url.'/csv.gif';
        echo CHtml::link("<img src=\"$imgUrl\" class=\"img_link\" title=\"".Yii::t('lms', 'print')."\">",
                        "#", array_merge($this->htmlOptions, array('onclick'=>'return exportToCsv();')));
        self::$count++;
        if (self::$count == 1) {
            Yii::app()->clientScript->registerCoreScript('jquery');
            Yii::app()->clientScript->registerCoreScript('yii');

            echo CHtml::script("
                var firstTime = true;
                var formCsv;
                function exportToCsv()
                {
                    if (firstTime) {
                        \$('<form id=\"csvExportForm\" method=\"POST\" action=\"".Yii::app()->urlManager->createUrl('csv/index')."\">').appendTo('body');

                        formCsv = \$('#csvExportForm').get(0);
                        arrayEl = \$('{$this->table}').get();
                        for (var i=0; i<arrayEl.length; i++) {
                            rows = arrayEl[i].rows;
                            for (var j=0; j<rows.length; j++){
                                if (rows[j].className.indexOf('{$this->ignoredRow}') === -1) {
                                    cells = rows[j].cells;
                                    for (var k=0; k<cells.length; k++){
                                        if (cells[k].className.indexOf('{$this->ignoredCol}') === -1) {
                                            var input = document.createElement('input');
                                            input.setAttribute('type', 'hidden');
                                            input.setAttribute('name', 'tCells['+i+']['+j+']['+k+']');
                                            input.setAttribute('value', cells[k].innerHTML);
                                            formCsv.appendChild(input);
                                        }
                                    }
                                }
                            }
                        }
                        input = document.createElement('input');
                        input.setAttribute('type', 'hidden');
                        input.setAttribute('name', 'csvFile');
                        input.setAttribute('value', '{$this->csvFile}');
                        formCsv.appendChild(input);

                        firstTime = false;
                    }
                    formCsv.submit();
                    return false;
                }
            ");
        }
    }

}
